package com.sinosoft.perfect.system._unit.dataFormat;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

import com.sinosoft.perfect.system._.po.TUnit;
import com.sinosoft.perfect.system._.util.XmlUtil;
import com.sinosoft.perfect.system._unit.formBean.UnitForm;

public class UnitTreeDataFormat_DHX implements IUnitTreeDataFormat {

	@Override
	public String dataFormatUnitTree(List<UnitForm> unitFormList) {
		Document document = XmlUtil.createDocument();
		Element rootElement = XmlUtil.createRootElement(document, "tree");
		rootElement.addAttribute("id", "0");

		if (unitFormList != null && unitFormList.size() != 0) {
			for (int i = 0; i < unitFormList.size(); i++) {
				TUnit unit = unitFormList.get(i);

				if (unit.getUnitLevel() == 1) {
					Element nowNode = XmlUtil.createElement("item");
					XmlUtil.editElementAttribute(nowNode, "id", unit.getUnitId());
					XmlUtil.editElementAttribute(nowNode, "text", unit.getUnitName());
					if ("0".equals(unit.getStatus())) {
						XmlUtil.editElementAttribute(nowNode, "style", "color:red");
					}
					XmlUtil.addElementChild(rootElement, nowNode);
					addUnitChild(unit.getUnitId(), unitFormList, nowNode);
				}
			}
		}
		return XmlUtil.getDocumentToXmlString(document);
	}

	private <T> void addUnitChild(String superId, List<T> unitList, Element parentNode) {
		for (int i = 0; i < unitList.size(); i++) {
			TUnit unit = (TUnit) unitList.get(i);
			Element nowNode = XmlUtil.createElement("item");
			XmlUtil.editElementAttribute(nowNode, "id", unit.getUnitId());
			XmlUtil.editElementAttribute(nowNode, "text", unit.getUnitName());
			if ("0".equals(unit.getStatus())) {
				XmlUtil.editElementAttribute(nowNode, "style", "color:red");
			}

			if (superId.equals(unit.getSuperUnitId())) {
				XmlUtil.addElementChild(parentNode, nowNode);
				if (hasUnitChild(unitList, unit.getUnitId()))
					addUnitChild(unit.getUnitId(), unitList, nowNode);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private <T> boolean hasUnitChild(List<T> unitList, String superId) {
		Iterator<TUnit> unitIterator = (Iterator<TUnit>) unitList.iterator();
		boolean result = false;
		while (unitIterator.hasNext()) {
			TUnit unit = unitIterator.next();
			if (superId.equals(unit.getSuperUnitId())) {
				result = true;
				break;
			}
		}
		return result;
	}

}
